<template>
	<view class="gift-items">
		<up-image :src="gift.image" mode="widthFix" width="100px"></up-image>
		<view class="gift-name">
			<view class="gift-name-its">
				{{ gift.name }}
			</view>
			<view class="prices">
				<text class="prices-unit">￥</text>
				<text class="prices-money">{{ gift.prices }}</text>
			</view>
		</view>
	</view>
	<up-card :show-head="false" :show-foot="false">
		<template #body>
			<view>产品选择</view>
			<view class="product-lst">
				<view class="product-its" v-for="pro in gift.product" @tap="checkedPro(pro)">
					<view class="product-name">
						{{ pro.productData.name }} <text style="color: #007aff;"
							@tap="detailProduct(pro.product)">查看</text>
						<view class="prices">价值：￥{{ pro.price }}</view>
					</view>
					<view class="icons">
						<up-icon name="checkmark-circle" size="22"
							:color="gift?.checked.some(its=>its === pro.product)?'#007aff':''"></up-icon>
					</view>
				</view>

			</view>
		</template>
	</up-card>
	<up-card :show-head="false" :show-foot="false">
		<template #body>
			<view class="recode-form">
				<view class="recode-form-label">
					礼包领取手机号
				</view>
				<view class="recode-form-input">
					<up-input v-model="formData.mobile"></up-input>
				</view>
			</view>
			<view class="product-btn">
				<up-button type="primary" :text="!payType?'立即领取':'立即购买'" shape="circle" @tap="payment"></up-button>
			</view>
		</template>
	</up-card>
</template>

<script setup>
	import {
		computed,
		reactive,
		ref
	} from 'vue';
	import {
		onShow
	} from "@dcloudio/uni-app"
	import {
		getQuery
	} from '@/utils/common';
	import {
		attrData,
		codeRecharge,
		giftPayment
	} from '@/utils/api/api';
	// import wx from "jweixin-module"
	const gift = ref({})
	const code = computed(() => {
		return uni.getStorageSync("code")
	})
	const payType = computed(() => {
		return code.value ? false : true
	})
	const formData = reactive({
		code: "",
		mobile: ""
	})
	const checkedPro = pro => {
		if (pro.type === 1) return;
		//判断是否已有单选的产品
		let _gift = [];
		gift.value.checked.forEach(its => {
			if (!gift.value.radio.some(it => it === its)) {
				_gift.push(its)
			}
		})
		_gift.push(pro.product)
		gift.value.checked = _gift
	}
	onShow(() => {
		const query = getQuery()
		if (query.options.id) {
			attrData(query.options.id).then((res) => {
				gift.value = res.result
			})
		}
		if (query.options.openid) {
			uni.setStorageSync("openid", query.options.openid)
		}
	})
	const payment = () => {
		if (!payType.value && !formData.code) {
			formData.code = code.value
		}
		if (!/^1[2-9]\d{9}$/.test(formData.mobile)) {
			return uni.showToast({
				title: "请输入领取礼包手机号",
				icon: "none"
			})
		}
		uni.showLoading({
			mask: true
		})
		let product = [];
		let pri = 0;
		gift.value.product.forEach(its => {
			if (gift.value.checked.some(it => it === its.product)) {
				product.push({
					id: its.product,
					number: its.number,
					money: its.price
				})
				pri += parseFloat(its.price)
			}
		})
		//处理提交数据
		let data = {
			code: formData.code,
			attr: gift.value.id,
			pack: gift.value.pack,
			product,
			mobile: formData.mobile
		}
		if (!payType.value) {
			codeRecharge(data).then((res) => {
				uni.hideLoading()
				uni.removeStorageSync("code")
				uni.setStorageSync("mobile", {
					mobile: formData.mobile,
					timer: new Date().getTime()
				})
				uni.navigateTo({
					url: "/pages/paySuccess/paySuccess?code=" + code.value
				})
			}).catch((res) => {
				// console.log(res)
				uni.hideLoading()
				uni.showToast({
					title: res,
					icon: "none"
				})
			})
		} else {
			const payM = () => {
				let str = uni.getSystemInfoSync()
				if (!/MicroMessenger/.test(str.ua)) {
					uni.hideLoading()
					return uni.showToast({
						title: '请在微信中打开支付！',
						icon: "none"
					})
				}
				let openid = uni.getStorageSync("openid")
				if (!openid) {
					location.href = "http://admin.zhixingjiuzhou.com/wechat/pay?id=" + gift.value.id
					return
				}
				data.openid = openid;
				giftPayment(data).then((res) => {
					// console.log(res)
					let payParam = res.result.payParam
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
							appId: payParam['app_id'],
							timeStamp: payParam['time_stamp'],
							nonceStr: payParam['nonce_str'], // 支付签名随机串，不长于 32 位  
							package: payParam[
							'package'], // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）  
							signType: payParam['sign_type'], // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'  
							paySign: payParam['pay_sign'], // 支付签名  
						},
						function(r) {
							uni.hideLoading()
							let msg = r.err_msg ? r.err_msg : r.errMsg;
							switch (msg) {
								case 'get_brand_wcpay_request:ok': //支付成功时  
									uni.removeStorageSync("pro_id")
									uni.setStorageSync("mobile", {
										mobile: formData.mobile,
										timer: new Date().getTime()
									})
									uni.navigateTo({
										url: "/pages/paySuccess/paySuccess?order=" + res.result
											.outTradeNo
									})
									break;
								default: //支付失败时
									uni.showToast({
										title: msg,
										icon: "none"
									})
									break;
							}
						})
				}).catch(res => {
					uni.showToast({
						title: res,
						icon: "none"
					})
				})
			}

			if (pri < parseFloat(gift.value.prices)) {
				uni.hideLoading()
				uni.showModal({
					content: "当前选中的礼品数量价值小于支付金额，确认提交支付？",
					complete(res) {
						if (res.confirm) {
							uni.showLoading({
								mask: true
							})
							payM()
						}
					}
				})
			} else {
				payM()
			}
		}
	}

	const detailProduct = id => {
		uni.navigateTo({
			url: "/pages/product/product?id=" + id
		})
	}
</script>

<style lang="scss">
	.gift-items {
		padding: 15px;
		display: flex;
		width: 100vw;
		box-sizing: border-box;

		.gift-name {
			margin-left: 10px;
			line-height: 1.75;
			width: calc(100% - 110px);
			flex-basis: calc(100% - 110px);

			.gift-name-its {
				font-weight: 600;
			}
		}
	}

	.product-its {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 10px 0;

		.prices {
			font-size: .8rem;
		}
	}

	.recode-form {
		margin: 10px 0;

		.recode-form-label {
			margin-bottom: 10px;
		}
	}
</style>